<template>
  <div class="moni-wrap flex gap-5 mt-4">
    <div class="w-96">
      <!-- <div class="text-2xl font-bold">可选择对比参数</div>
      <div>参数</div> -->
      <div class="moni-bg relative">
        <img class="w-full h-72" src="@/assets/images/moni-bg.png" />
        <div class="p-8 absolute top-0 left-0 right-0 bottom-0 flex flex-col justify-between">
          <div class="text-2xl font-bold">经营期内林木生长动态情况</div>
          <div class="flex flex-col gap-4">
            <div class="flex items-center justify-between text-base bg-white rounded-md px-4 cursor-pointer h-11"
              @click="handlePostMessage('混交栽培模式')">
              <div class="flex items-center gap-2">
                <img src="@/assets/icons/hunjiao.png" />
                <span class="font-bold">混交栽培模式</span>
              </div>
              <img src="@/assets/icons/arrow.png" />
            </div>
            <div class="flex items-center justify-between text-base bg-white rounded-md px-4 cursor-pointer h-11"
              @click="handlePostMessage('桉树中径材用材林栽培模式')">
              <div class="flex items-center gap-2">
                <img src="@/assets/icons/gaochan.png" />
                <span class="font-bold">桉树中径材用材林栽培模式</span>
              </div>
              <img src="@/assets/icons/arrow.png" />
            </div>
            <div class="flex items-center justify-between text-base bg-white rounded-md px-4 cursor-pointer h-11"
              @click="handlePostMessage('桉树大径材用材林栽培模式')">
              <div class="flex items-center gap-2">
                <img src="@/assets/icons/linxia.png" />
                <span class="font-bold">桉树大径材用材林栽培模式</span>
              </div>
              <img src="@/assets/icons/arrow.png" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="flex-1">
      <div class="text-2xl font-bold mb-3">经营期内林木生长动态情况</div>
      <div>
        <div ref="echartRef" class="echart-container mb-3"></div>
        <div class="flex justify-end relative z-900">
          <el-button type="primary" color="#2B6E50" @click="handleExport">报告导出</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, computed } from 'vue'
import * as echarts from 'echarts'
import type { EChartsOption, EChartsType } from 'echarts'
import { downloadZip } from '@/api/forest-management'
import { getEchartsData } from '@/api/forest-management'
import { smaple } from './smaple'

// 类型定义
interface ChartData {
  carbon_data: number[]
  diameter_data: number[]
  economic_data: number[]
  height_data: number[]
  volume_data: number[]
}

interface RadarData {
  indicators: Array<{ name: string; max: number }>
  data: Array<{ name: string; value: number[] }>
}

// 常量定义
const CHART_COLORS = {
  primary: '#2B6E50',
  secondary: '#91cc75',
  diameter: '#5470c6',
  height: '#91cc75',
  volume: '#fac858',
  carbon: '#ee6666',
  economic: '#73c0de',
} as const

const MIXED_CULTIVATION_KEYS = {
  eucalyptus: '混交栽培模式-桉树',
  acacia: '混交栽培模式-黑木相思',
} as const

// 响应式数据
const chartData = ref<ChartData>({
  carbon_data: [],
  diameter_data: [],
  economic_data: [],
  height_data: [],
  volume_data: [],
})

const radarData = ref<RadarData>({ indicators: [], data: [] })
const years = ref<string[]>([])
const planMaking = ref<any[]>([])
const currentEvent = ref('桉树中径材用材林栽培模式')

// 计算属性
const isMixedMode = computed(() => currentEvent.value === '混交栽培模式')

const legendData = computed(() => {
  return isMixedMode.value
    ? ['桉树', '黑木相思', '混交-黑木相思', '混交-桉树']
    : ['桉树大径材', '桉树中径材', '混交-黑木相思', '混交-桉树']
})

const getChartOptions = (): EChartsOption => {

  return {
    title: [
      {
        text: '胸径',
        left: '16.5%',
        top: '1%',
        textAlign: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
        },
      },
      {
        text: '树高',
        left: '50%',
        top: '1%',
        textAlign: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
        },
      },
      {
        text: '蓄积量',
        left: '83.5%',
        top: '1%',
        textAlign: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
        },
      },
      {
        text: '碳储量',
        left: '20%',
        top: '54%',
        textAlign: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
        },
      },
      {
        text: '经济效益',
        left: '55%',
        top: '54%',
        textAlign: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
        },
      },
      {
        text: '综合效益雷达图',
        left: '85%',
        top: '54%',
        textAlign: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
        },
      },
    ],
    tooltip: {
      trigger: 'item',
      axisPointer: {
        type: 'cross',
      },
      formatter: function (params: any) {
        // 如果是雷达图数据
        if (params.componentType === 'radar') {
          const { seriesName, value } = params
          const indicators = ['蓄积量', '胸径', '树高', '碳储量', '经济效益']
          const units = ['m³', 'cm', 'm', 't', '元']

          let content = `<div style="font-weight: bold; margin-bottom: 8px;">${seriesName}</div>`

          if (Array.isArray(value)) {
            value.forEach((val: number, index: number) => {
              if (index < indicators.length) {
                content += `<div style="margin: 4px 0;">
                  <span style="display: inline-block; width: 8px; height: 8px; background: ${params.color}; border-radius: 50%; margin-right: 8px;"></span>
                  ${indicators[index]}: <strong>${val.toFixed(1)} ${units[index]}</strong>
                </div>`
              }
            })
          }

          return content
        }

        // 折线图的默认处理
        return `${params.seriesName}<br/>${params.name}: ${params.value}`
      }
    },
    legend: {
      data: legendData.value,
      left: '68%',
      top: '95%',
      orient: 'horizontal',
      textStyle: {
        fontSize: 16,
        color: '#333',
      },
      itemWidth: 12,
      itemHeight: 8,
      itemGap: 6,
    },
    grid: [
      {
        left: '0',
        right: '68%',
        top: '4%',
        bottom: '52%',
      },
      {
        left: '37%',
        right: '33.75%',
        top: '4%',
        bottom: '52%',
      },
      {
        left: '71%',
        right: '0',
        top: '4%',
        bottom: '52%',
      },
      {
        left: '0',
        right: '68%',
        top: '58%',
        bottom: '5%',
      },
      {
        left: '37%',
        right: '33.75%',
        top: '58%',
        bottom: '5%',
      },
    ],
    radar: {
      center: ['84%', '75%'],
      radius: '28%',
      indicator: [
        { name: '蓄积量', max: 350, min: 0 },
        { name: '胸径', max: 30, min: 0 },
        { name: '树高', max: 35, min: 0 },
        { name: '碳储量', max: 180, min: 0 },
        { name: '经济效益', max: 2000, min: 0 },
      ],
      splitNumber: 4, // 控制分割段数，避免刻度过密
      axisName: {
        fontSize: 16,
        color: '#333',
        fontWeight: 'bold',
      },
      axisLabel: {
        show: true,
        fontSize: 16,
        color: '#666',
        formatter: function (value: number, indicator: any) {
          // 根据不同指标格式化显示
          if (indicator.name === '经济效益') {
            return value >= 1000 ? (value / 1000).toFixed(1) + 'k' : value.toString()
          }
          return value.toString()
        }
      },
      splitArea: {
        show: true,
        areaStyle: {
          color: ['rgba(43, 110, 80, 0.05)', 'rgba(43, 110, 80, 0.1)']
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(43, 110, 80, 0.3)'
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(43, 110, 80, 0.5)'
        }
      },
    },
    xAxis: [
      {
        type: 'category',
        data: years.value,
        gridIndex: 0,
        axisLabel: {
          rotate: 45,
          fontSize: 16,
        },
      },
      {
        type: 'category',
        data: years.value,
        gridIndex: 1,
        axisLabel: {
          rotate: 45,
          fontSize: 16,
        },
      },
      {
        type: 'category',
        data: years.value,
        gridIndex: 2,
        axisLabel: {
          rotate: 45,
          fontSize: 16,
        },
      },
      {
        type: 'category',
        data: years.value,
        gridIndex: 3,
        axisLabel: {
          rotate: 45,
          fontSize: 16,
        },
      },
      {
        type: 'category',
        data: years.value,
        gridIndex: 4,
        axisLabel: {
          rotate: 45,
          fontSize: 16,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        gridIndex: 0,
        name: '胸径 (cm)',
        nameLocation: 'middle',
        nameGap: 30,
        nameTextStyle: {
          fontSize: 16,
        },
        axisLabel: {
          fontSize: 16,
        },
      },
      {
        type: 'value',
        gridIndex: 1,
        name: '树高 (m)',
        nameLocation: 'middle',
        nameGap: 30,
        nameTextStyle: {
          fontSize: 16,
        },
        axisLabel: {
          fontSize: 16,
        },
      },
      {
        type: 'value',
        gridIndex: 2,
        name: '蓄积量 (m³)',
        nameLocation: 'middle',
        nameGap: 30,
        nameTextStyle: {
          fontSize: 16,
        },
        axisLabel: {
          fontSize: 16,
        },
      },
      {
        type: 'value',
        gridIndex: 3,
        name: '碳储量 (t)',
        nameLocation: 'middle',
        nameGap: 30,
        nameTextStyle: {
          fontSize: 16,
        },
        axisLabel: {
          fontSize: 16,
        },
      },
      {
        type: 'value',
        gridIndex: 4,
        name: '经济效益 (元)',
        nameLocation: 'middle',
        nameGap: 30,
        nameTextStyle: {
          fontSize: 16,
        },
        axisLabel: {
          fontSize: 16,
        },
      },
    ],
    series: [],
  }
}

// 图表实例管理
const echartRef = ref<HTMLDivElement | null>(null)
let myChart: EChartsType | null = null

// 创建折线图系列的工厂函数
const createLineSeries = (name: string, data: number[], axisIndex: number, color: string, isDashed = false) => ({
  name,
  type: 'line' as const,
  data,
  xAxisIndex: axisIndex,
  yAxisIndex: axisIndex,
  smooth: true,
  lineStyle: {
    color,
    width: 2,
    ...(isDashed && { type: 'dashed' })
  },
  itemStyle: { color },
})

// 创建雷达图系列的工厂函数
const createRadarSeries = (item: any, index: number, colors: string[], radarNames: string[]) => {
  const displayName = radarNames[index] || item.name
  return {
    name: displayName,
    type: 'radar' as const,
    data: [{ value: item.value, name: displayName }],
    lineStyle: { color: colors[index % colors.length], width: 3 },
    itemStyle: {
      color: colors[index % colors.length],
      borderWidth: 2,
      borderColor: '#fff'
    },
    areaStyle: {
      opacity: 0.15,
      color: colors[index % colors.length]
    },
    symbol: 'circle',
    symbolSize: 6,
  }
}

const handleEchart = () => {
  if (!echartRef.value) return

  // 先销毁之前的图表实例，避免内存泄漏
  if (myChart) {
    myChart.dispose()
    myChart = null
  }

  const options = getChartOptions()

  // 如果有雷达图数据，更新雷达图的indicator配置
  if (radarData.value.indicators.length > 0) {
    options.radar = {
      center: ['84%', '75%'],
      radius: '28%',
      indicator: radarData.value.indicators,
      axisName: {
        fontSize: 16,
        color: '#333',
        fontWeight: 'bold',
      },
      splitArea: {
        show: true,
        areaStyle: {
          color: ['rgba(43, 110, 80, 0.05)', 'rgba(43, 110, 80, 0.1)']
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(43, 110, 80, 0.3)'
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(43, 110, 80, 0.5)'
        }
      },
    }
  }

  // 配置折线图和雷达图的系列数据
  const series: any[] = []

  if (isMixedMode.value) {
    // 混交栽培模式 - 双线显示
    series.push(
      // 胸径对比
      createLineSeries('桉树-胸径', chartData.value.diameter_data, 0, CHART_COLORS.primary),
      createLineSeries('黑木相思-胸径', smaple.diameter_data[MIXED_CULTIVATION_KEYS.acacia], 0, CHART_COLORS.secondary, true),

      // 树高对比
      createLineSeries('桉树-树高', chartData.value.height_data, 1, CHART_COLORS.primary),
      createLineSeries('黑木相思-树高', smaple.height_data[MIXED_CULTIVATION_KEYS.acacia], 1, CHART_COLORS.secondary, true),

      // 蓄积量对比
      createLineSeries('桉树-蓄积量', chartData.value.volume_data, 2, CHART_COLORS.primary),
      createLineSeries('黑木相思-蓄积量', smaple.volume_data[MIXED_CULTIVATION_KEYS.acacia], 2, CHART_COLORS.secondary, true),

      // 碳储量对比
      createLineSeries('桉树-碳储量', chartData.value.carbon_data, 3, CHART_COLORS.primary),
      createLineSeries('黑木相思-碳储量', smaple.carbon_data[MIXED_CULTIVATION_KEYS.acacia], 3, CHART_COLORS.secondary, true),

      // 经济效益对比
      createLineSeries('桉树-经济效益', chartData.value.economic_data, 4, CHART_COLORS.primary),
      createLineSeries('黑木相思-经济效益', smaple.economic_data[MIXED_CULTIVATION_KEYS.acacia], 4, CHART_COLORS.secondary, true)
    )
  } else {
    // 非混交模式 - 单线显示
    series.push(
      createLineSeries('胸径', chartData.value.diameter_data, 0, CHART_COLORS.diameter),
      createLineSeries('树高', chartData.value.height_data, 1, CHART_COLORS.height),
      createLineSeries('蓄积量', chartData.value.volume_data, 2, CHART_COLORS.volume),
      createLineSeries('碳储量', chartData.value.carbon_data, 3, CHART_COLORS.carbon),
      createLineSeries('经济效益', chartData.value.economic_data, 4, CHART_COLORS.economic)
    )
  }

  // 添加雷达图系列数据
  if (radarData.value.data.length > 0) {
    const colors = [CHART_COLORS.primary, CHART_COLORS.diameter, CHART_COLORS.secondary, CHART_COLORS.volume]
    const radarNames = ['桉树大径材', '桉树中径材', '混交-黑木相思', '混交-桉树']

    radarData.value.data.forEach((item, index) => {
      series.push(createRadarSeries(item, index, colors, radarNames))
    })
  }

  options.series = series

  // 创建新的图表实例
  myChart = echarts.init(echartRef.value)
  myChart.setOption(options, true) // 第二个参数为true表示不合并，直接替换
}

const EVENT_MAP = {
  桉树中径材用材林栽培模式: '桉树中径材用材林经营方案-桉树',
  桉树大径材用材林栽培模式: '桉树大径材用材林经营方案-桉树',
  混交栽培模式: '混交栽培模式',
}

type EventType = keyof typeof EVENT_MAP

// 数据更新函数
const updateChartData = (data: any, event: EventType) => {
  const mappedKey = EVENT_MAP[event]

  if (event === '混交栽培模式') {
    // 混交模式使用桉树数据作为主要显示
    const eucalyptusKey = MIXED_CULTIVATION_KEYS.eucalyptus
    chartData.value = {
      carbon_data: data.carbon_data[eucalyptusKey] || [],
      diameter_data: data.diameter_data[eucalyptusKey] || [],
      economic_data: data.economic_data[eucalyptusKey] || [],
      height_data: data.height_data[eucalyptusKey] || [],
      volume_data: data.volume_data[eucalyptusKey] || [],
    }
  } else {
    chartData.value = {
      carbon_data: data.carbon_data[mappedKey] || [],
      diameter_data: data.diameter_data[mappedKey] || [],
      economic_data: data.economic_data[mappedKey] || [],
      height_data: data.height_data[mappedKey] || [],
      volume_data: data.volume_data[mappedKey] || [],
    }
  }
}

// 获取数据的主函数
const handleViewVis = (data: any, event: EventType) => {
  try {
    currentEvent.value = event

    // 更新图表数据
    updateChartData(data, event)

    // 更新雷达图数据
    radarData.value = data.radar_data || { indicators: [], data: [] }

    // 更新其他数据
    years.value = data.years || []


    // 重新渲染图表
    handleEchart()
  } catch (error) {
    console.error('数据处理错误:', error)
  }
}

// 获取图表数据
const echartsData = ref<any>('')
const getEchartData = async (converstionId: string, event: EventType, plan: any) => {
  planMaking.value = plan || []
  const res = await getEchartsData({ converstionId })
  echartsData.value = res
  const data = JSON.parse(res)
  handleViewVis(data, event)
  return res
}

// 窗口大小变化处理
const handleResize = () => {
  if (myChart) {
    myChart.resize()
  }
}

// 生命周期管理
onMounted(() => {
  // handleViewVis(smaple, '混交栽培模式', '')
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
  window.removeEventListener('resize', handleResize)
})

// 事件处理函数
const handlePostMessage = (model: string) => {
  const message = { type: 'message', content: echartsData.value, model }
  console.log('发送消息:', message);

  window.parent.postMessage(message, '*')
}

const handleExport = async () => {
  try {
    const res = await downloadZip(planMaking.value)
    if (res.code === 200) {
      window.open(res.data, '_blank')
    }
  } catch (error) {
    console.error('导出失败:', error)
  }
}

defineExpose({
  handleViewVis,
  getEchartData,
})
</script>
<style scoped lang="scss">
.moni-wrap {
  .el-button {
    width: 240px;
    height: 42px;
    font-size: 18px;
    border-radius: 8px;

    :deep(span) {
      font-weight: bold;
    }
  }

  .echart-container {
    height: calc(100vh - 320px);
    width: calc(100vw - 720px);
  }

  .echart-wrap {
    width: calc((100vw - 750px) / 3);
    height: calc((100vh - 320px) / 2);
    // background: #f00;
  }
}
</style>
